<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/12
 * Time: 下午5:29
 */

namespace Superadmin\Model;


use Think\Model\RelationModel;

class AdminRoleModel extends RelationModel
{
    protected $connection = 'DB_CONFIG1';
    protected $table      = 'admin_role';
    protected $prefix     = 'tp_';
    protected $_validate = array(
        array('name', 'require', '新角色名称为必须'), //新角色名称为必须
    );

    protected $_link = array(
        'role_priv' => array(
            'mapping_type'  => RelationModel::MANY_TO_MANY,
            'class_name'    => 'menu',
            'foreign_key'   => 'role_id',
            'relation_foreign_key'=>'menu_id',
            'relation_table' => 'tp_admin_auth',
            'auto_prefix' => true
        )
    );

    //检测是否重复
    public function is_exists($id, $name)
    {
        $where = array(
            'name' => $name,
            'id'   => array('neq', $id),
        );
        return $this->where($where)->find();
    }

    //所有禁用的角色
    public function alldisabled()
    {
        $list = $this->where(array('status'=> 0))->field('id,name')->select();
        return $list;
    }

    //所有可用角色
    public function allabled()
    {
        $list = $this->where(array('status'=> 1))->field('id,name')->select();
        return $list;
    }

    //获取角色的所有可以操作的权限 并缓存S
    public function allauth($role_id)
    {
       if(S('role_auth_'. $role_id)) return S('role_auth_'. $role_id);
       $list = D('admin_auth')->where(array('role_id' => $role_id))->select();
       if(!$list) return $list;
       $auth = i_array_column($list, 'menu_id');
       S('role_auth_'. $role_id, $auth, 86400);
       return $auth;
    }
}